package org.dingyom.user.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登陆拦截 和 权限拦截
 */
@Configuration
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登陆拦截 用token判断是否登陆
        String token = request.getHeader("token");//获取请求头
        if (!StringUtils.isEmpty(token)){//前端传过来的额token不为空

            //获取redis中的token值
            Object obj = redisTemplate.opsForValue().get(token);
            if (obj != null) {//redis中token也存在 没过期
                //刷新过期时间 30分钟
                redisTemplate.opsForValue().set(token, obj, 30, TimeUnit.MINUTES);
                return true;//放行
            }
        }
        //权限拦截 有时间了再来做 TODO

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();//关闭写入流
        return false;//拦截
    }
}
